package com.qubaopen.core.utils;

import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * 正则表达式工具类，支持*和？通配符的校验功能
 * 
 * @author DELL
 * 
 */
public class RegexUtils {

	private static final String PATTERN_LINE_START = "^";

	private static final String PATTERN_LINE_END = "$";

	private static final char[] META_CHARACTERS = { '$', '^', '[', ']', '(',
			')', '{', '}', '|', '+', '.', '\\' };

	/**
	 * match function, support '*' and '?'. The function is based on regex.
	 * 
	 * @param pattern
	 * @param str
	 * @return
	 */
	public static boolean wildcardMatch(String pattern, String str) {
		pattern = convertToRegexPattern(pattern);
		return Pattern.matches(pattern, str);
	}

	private static String convertToRegexPattern(String wildcardString) {
		String result = PATTERN_LINE_START;
		char[] chars = wildcardString.toCharArray();
		for (char ch : chars) {
			if (Arrays.binarySearch(META_CHARACTERS, ch) >= 0) {
				result += "\\" + ch;
				continue;
			}
			switch (ch) {
			case '*':
				result += ".*";
				break;
			case '?':
				result += ".{0,1}";
				break;
			default:
				result += ch;
			}
		}
		result += PATTERN_LINE_END;
		return result;
	}

}
